<template>
  <div>
    <img
        :data-src="m_src"
        alt=""
        class="lazyload"
        style="width: 100%"
    />
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue';
export default defineComponent({
  name: "LazyLoadImage",
  props: {
    m_src: {
      type: String,
      required: true
    }
  },
  mounted() {
    // 创建 IntersectionObserver 实例
    const imageObserver = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (entry.isIntersecting) {
          const img = entry.target as HTMLImageElement;
          img.src = img.dataset.src; // 将 data-src 设置为 src
          imageObserver.unobserve(img); // 停止观察当前图片
        }
      });
    });

    // 选择当前组件中的图片
    const imgElement = this.$el.querySelector('img.lazyload');
    if (imgElement) {
      imageObserver.observe(imgElement); // 开始观察图片
    }
  }
});
</script>

<style scoped>
img.lazyload {
  opacity: 0;
  transition: opacity 0.3s; /* 增加渐变过渡效果 */
}
img.lazyload[src] {
  opacity: 1; /* 当图片加载后进行淡入效果 */
}
</style>
